import {reqGetCode, reqRegister, reqUserLogin, reqUserInfo, reqUserLogout} from '@/api/index.js';

// 材料：
let state = {
    code: '',
    token: localStorage.getItem("TOKEN"),
    nickName: ''
};

// 加工：
let getters = {};

// 厨师：
let mutations = {
    GETCODE(state, value) {
        state.code = value;
    },
    SET_TOKEN(state, value) {
        state.token = value;
    },
    SET_NICKNAME(state, value) {
        state.nickName = value;
    },
    SET_USERINFO(state, value) {
        state.nickName = value;
    },
    CLEAR(state) {
        state.token = '';
        state.nickName = '';
        localStorage.removeItem('TOKEN');
    }
};

// 迎宾：
let actions = {
    async getCode({commit, state, dispatch}, phone) {
        let result = await reqGetCode(phone);
        if (result.code === 200) {
            commit('GETCODE', result.data);
            return result.data;
        } else {
            return Promise.reject();
        }
    },
    async registerUser({commit, state, dispatch}, obj) {
        let result = await reqRegister(obj);
        console.log(result);
        if (result.code === 200) {
            return result;
        } else {
            return Promise.reject(new Error(result.message));
        }
    },
    async userLogin({commit, state, dispatch}, data) {
        let result = await reqUserLogin(data);
        console.log(result);
        if (result.code === 200) {
            commit('SET_TOKEN', result.data.token);
            commit('SET_NICKNAME', result.data.nickName);
            localStorage.setItem('TOKEN', result.data.token);
            return result;
        } else {
            return Promise.reject(new Error(result.message));
        }
    },
    async getUserInfo({commit, state, dispatch}) {
        let result = await reqUserInfo();
        if (result.code === 200) {
            commit('SET_USERINFO', result.data.nickName);
            return result;
        } else {
            return Promise.reject();
        }
    },
    async logout({commit, state, dispatch}) {
        let result = await reqUserLogout();
        if (result.code === 200) {
            commit('CLEAR');
            return result;
        } else {
            return Promise.reject(new Error(result.message));
        }
    }
};

// 对外暴露
export default {
    state,
    mutations,
    actions,
    getters
};



